<?php
namespace App\Services;

use App\Goods;
use App\RoleMenuPermission;
use App\Lib\Util\QueryPager;
use DB;


class GoodsService
{
    /*public function getGoods(){
        $goods = new Goods();

    }*/

    public function createRoute($route)
    {
        return Goods::create($route);
    }

    public function saveGoods(Array $input)
    {
        Goods::create([
           'commodity_name'    =>   $input['commodity_name'],
           'commodity_price'    =>   $input['commodity_price'],
           'commodity_number'    =>   $input['commodity_number'],
           'commodity_id'    =>   1,//目前先写成这样。开始设置的时候不能为空，外键不会关联。
            'brand_id'  =>  1//目前先写成这样。开始设置的时候不能为空，外键不会关联。
        ]);
    }

    private function baseQuery()
    {
        return Goods::select('id','commodity_id', 'commodity_name', 'commodity_price', 'commodity_number', 'brand_id');
    }

    public function getGoods(Array $input, $paging = true)
    {
        $query = $this->baseQuery();

        if (!empty($input['commodity_name'])) {
            $query->where('commodity_name', 'like' , '%'.$input['commodity_name'].'%');
        }

        $pager = new QueryPager($query);

        return $paging ? $pager->doPaginate($input, 'commodity_name') :
            $pager->queryWithoutPaginate($input, 'commodity_name');
    }

    public function deleteGoods($commodityId)
    {
        DB::transaction(function () use ($commodityId) {
            RoleMenuPermission::where('commodity_id', $commodityId)->delete();

            $goods = Goods::findOrFail($commodityId);
            $goods->delete();
        });
    }
}
